<template>
  <BasicModal
    v-bind="$attrs"
    :showFooter="true"
    @register="registerSettingModal"
    @ok="handleSettingSubmit"
    width="600px"
    title="批量设置调入仓库"
  >
    <BasicForm @register="registerSettingForm" />
  </BasicModal>
</template>

<script lang="ts" setup name="BatchSetDcstockname">
  import { ref, computed, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';

  const emit = defineEmits(['success', 'register']);
  const { t } = useI18n();
  const { showMessage } = useMessage();

  // 存储选中的行数据
  const selectedRows = ref<any[]>([]);

  // 安全地更新特定字段，避免清空其他字段
  const safeUpdateFields = (updates: Record<string, any>) => {
    const currentValues = getFieldsValue();
    setFieldsValue({
      ...currentValues,
      ...updates,
    });
  };

  // 表单配置
  const formSchemas: FormSchema[] = [
    {
      label: t('调入仓库'),
      field: 'dcWarehouse',
      fieldLabel: 'dcWarehouseName',
      component: 'TreeSelect',
      componentProps: {
        api: basWarehouseTreeData,
        allowClear: true,
        placeholder: '请选择调入仓库',
        showSearch: true,
        canSelectParent: false,
        onChange: (value: string, label: string) => {
          console.log('选择的仓库:', value, label);
          // 使用安全的字段更新函数，只更新仓库相关字段
          safeUpdateFields({
            dcWarehouse: value,
            dcWarehouseCode: value,
            dcWarehouseName: label,
          });
        },
      },
      required: true,
    },
    {
      label: t('仓库编码'),
      field: 'dcWarehouseCode',
      component: 'Input',
      componentProps: {
        disabled: true,
        placeholder: '自动填充',
      },
    },
    {
      label: t('仓库名称'),
      field: 'dcWarehouseName',
      component: 'Input',
      componentProps: {
        disabled: true,
        placeholder: '自动填充',
      },
    },
  ];

  const [registerSettingForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: formSchemas,
    baseColProps: { lg: 24, md: 24 },
    showActionButtonGroup: false,
  });

  const [registerSettingModal, { setModalProps, closeModal }] = useModalInner(async (data: any) => {
    resetFields();
    selectedRows.value = data.selectedRows || [];

    // 使用 setTimeout 确保表单重置完成后再设置值
    setTimeout(() => {
      safeUpdateFields({
        selectedCount: selectedRows.value.length,
      });
    }, 0);

    setModalProps({ confirmLoading: false });
  });

  // 提交处理
  async function handleSettingSubmit() {
    try {
      const values = await validate();
      console.log('values', values);

      if (!values.dcWarehouse) {
        showMessage('请选择调入仓库！');
        return false;
      }

      if (selectedRows.value.length === 0) {
        showMessage('没有选中的行数据！');
        return false;
      }

      setModalProps({ confirmLoading: true });

      // 构造批量更新的数据
      const updateData = {
        // fdcstockname: values.dcWarehouse,
        fdcstockid: values.dcWarehouseCode,
        fdcstockno: values.dcWarehouseCode,
        fdcstockname: values.dcWarehouseName,
        selectedRows: selectedRows.value.map((row: any) => ({
          id: row.id,
          fentryid: row.fentryid,
        })),
      };

      // 触发成功事件，将数据传递给父组件
      emit('success', updateData);

      closeModal();
      return true;
    } catch (error) {
      console.error('批量设置失败:', error);
      showMessage('批量设置失败，请检查输入信息！');
      return false;
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
